<?php
// This class handles user login

class UserIdentity extends CUserIdentity
{
	/**
	 * Description: This method logs a user in if the username is active and if the username/password pair corresponds with the database
	 * Returns: True if no error, false otherwise
	 */
	public function authenticate()
	{
		// Retrieves user record
		$record = Users::model()->findByAttributes(array('user_name'=>$this->username, 'user_type_ID'=>Yii::app()->user->userTypeID, 'active'=>'1'));

		if($record===null) {
            $this->errorCode=self::ERROR_USERNAME_INVALID;
            $this->errorMessage='Username does not exist or password is incorrect.<br />';
		}
        else if($record->password!==$this->password) { //add md5 later
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
            $this->errorMessage='Username does not exist or password is incorrect.<br />';
        }
        else
        {
        	// Stores user ID in session
            $this->setState('userID', $record->user_ID);
            
            //Stores organization ID in session
            $this->setState('organizationID', $record->organization_ID);
            
            // Gets user role type ID
            $roleTypeID = $record->user_role_type_ID;
            
            // Finds user type
            $record = UserTypes::model()->findByAttributes(array('user_type_ID'=>Yii::app()->user->userTypeID));
            $userType = substr($record->user_type_description, 0, 1);
            
            // Stores user type and user role type in session
            $this->setState('userType', $userType);
            $this->setState('roleType', $roleTypeID);
            
            $this->errorCode=self::ERROR_NONE;
        }
        
        // Removes user type ID from session
        Yii::app()->user->setState('userTypeID', null);
        
        return !$this->errorCode;
	}
}
?>
